<template>
  <div>
    <el-row>
      <el-col :span="4">
        <el-button type="primary" @click="gatcat">选择车辆</el-button>
      </el-col>
      <el-col :span="3">
        <el-form-item label="备注">
        <el-input v-model="AddNewOrderForm.remark" ></el-input>
      </el-form-item>
      </el-col>

      <el-col  :push="1" :span="4">
        <el-form-item label="预约时间">
        <el-date-picker
          v-model="AddNewOrderForm.appointmentTime"
          type="datetime"
          placeholder="选择日期时间"
        ></el-date-picker>
      </el-form-item>
      </el-col>
    </el-row>
    <!-- 对话框 -->
    <el-dialog v-model="dialogVisible" width="80%" center @close="onDialogClose">
      <img :src="currentImage" alt="放大后的图片" class="enlarged-photo" />
    </el-dialog>

    <!-- 店铺信息列表 -->
    <el-space wrap>
      <el-card
        v-for="(shopItem, index) in shopList"
        :key="index"
        class="box-card"
        style="width: 350px; margin-bottom: 20px;"
      >
        <template #header>
          <div class="card-header">
            <span>店铺信息详情</span>
          </div>
        </template>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="店铺名称">{{ shopItem.shopName }}</el-descriptions-item>
          <el-descriptions-item label="店铺地址(经纬度)">{{ shopItem.shopAddress }}</el-descriptions-item>
          <el-descriptions-item label="店铺电话">{{ shopItem.shopPhone }}</el-descriptions-item>
          <el-descriptions-item label="营业执照">{{ shopItem.shopLicense }}</el-descriptions-item>
          <el-descriptions-item label="店铺评分">{{ shopItem.shopIntegral }}</el-descriptions-item>
          <el-descriptions-item label="店铺营业时间">{{ shopItem.businessHours }}</el-descriptions-item>
          <el-descriptions-item label="店铺头像">
            <img :src="shopItem.shopImage" alt="店铺头像" style="max-width:30px;" />
          </el-descriptions-item>
          <el-descriptions-item label="图片详情">
           <img :src="shopItem.shopPoto" alt="图片详情" style="max-width:30px;"   @click="showImage(shopItem.shopPoto)" />
           <!-- <pre>{{ shopItem.shopPoto }}</pre> -->
         </el-descriptions-item>
          <el-descriptions-item label="店铺描述">{{ shopItem.shopDescription }}</el-descriptions-item>
          <el-descriptions-item label="店铺服务范围描述">{{ shopItem.serviceDescription }}</el-descriptions-item>
        </el-descriptions>
        <!-- 按钮组 -->
        <div class="button-group">
          <el-button type="primary" @click="viewShopServices(shopItem)">查看商家服务</el-button>
        </div>
      </el-card>
    </el-space>

    <!-- 商家服务详情抽屉 -->
    <el-drawer v-model="isShow" title="商家服务详情" size="80%">
      <el-table :data="shopService" style="width: 100%">
        <el-table-column prop="serviceName" label="服务名称"></el-table-column>
        <el-table-column prop="details" label="详情"></el-table-column>
        <el-table-column prop="estimatedTime" label="预估时间(小时)"></el-table-column>
        <el-table-column prop="servicePrice" label="服务价格"></el-table-column>
        <el-table-column prop="terms" label="条款"></el-table-column>
        <<el-table-column label="服务详情图" width="100">
  <template #default="scope">
    <img 
      :src="scope.row.serviceImage" 
      style="max-width: 80px; max-height: 80px;" 
      class="service-image"
    />
  </template>
</el-table-column>

        <el-table-column label="服务必须物品">
          <template #default="scope">
            <div v-for="item in scope.row.serviceItems" :key="item.itemsId">
              单价：{{ item.unitPrice }} 数量：{{ item.quantity }} 价格：{{ item.price }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="服务流程">
          <template #default="scope">
            <div v-for="process in scope.row.serviceProcesses" :key="process.processesId">
              单价：{{ process.unitPrice }} 工时：{{ process.workingHours }} 价格：{{ process.processesPrice }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
      <template #default="scope">
        <el-button type="primary" @click="addservers(scope.row)">选择</el-button>
      </template>
    </el-table-column>
      </el-table>
    </el-drawer>

    <el-drawer v-model="drawer" title="选择车辆" size="80%">

      <el-table :data="carList" style="width: 100%">
      <el-table-column prop="licensePlate" label="车牌号" width="120"></el-table-column>
      <el-table-column prop="model" label="车辆类型" width="100"></el-table-column>
      <el-table-column prop="typeName" label="品牌" width="100"></el-table-column>
      <el-table-column prop="sub_types" label="品牌系列" width="120"></el-table-column>
      <el-table-column prop="carColor" label="车辆颜色" width="100"></el-table-column>
      <el-table-column label="行驶里程" width="120">
        <template #default="scope">{{ scope.row.mileage }} km</template>
      </el-table-column>
      <el-table-column label="图片" width="100">
        <template #default="scope">
          <img 
            :src="scope.row.carImage" 
            style="max-width: 60px; max-height: 60px;" 
          />
        </template>
      </el-table-column>
      <el-table-column prop="creationTime" label="创建时间" width="180">
        <template #default="scope">{{ formatDate(scope.row.creationTime) }}</template>
      </el-table-column>
      <el-table-column prop="maintenanceTime" label="下次保养时间" width="180">
        <template #default="scope">{{ formatDate(scope.row.maintenanceTime) }}</template>
      </el-table-column>
  
      <el-table-column prop="notes" label="备注" min-width="150"></el-table-column>


      <el-table-column label="操作" width="200">
      <template #default="scope">
        <el-button type="primary" @click="addcar(scope.row)">选择</el-button>
      </template>
    </el-table-column>
    </el-table>


    </el-drawer>

    

     

   


<el-row>
  <el-col>
    <el-button type="primary" @click="addorder">下单</el-button>
  </el-col>
</el-row>



  </div>
</template>

<script>
export default {
  name: 'ShopInfo',
  data() {
    return {
      PageForm: {
        pageNum: 1,
        pageSize: 20
      },
      shopList: [], // 用于存储多个店铺信息
      dialogVisible: false,
      currentImage: '',
      FindServiceUserForm: {
        shopId: null,
        serviceName: null,
        serviceCategoryId: null,
        state: null,
        servicePrice: "",
        pageForm: {
          pageNum: 1,
          pageSize: 20
        }
      },
      shopService: [],
      isShow: false,
      carList:[],
      SelectCarInfoForm:{
      },
      AddNewOrderForm:{
      shopId: null,
      carId: null,
      serviceId: null,
      totalAmount: null,
      appointmentTime: null,
      remark: '无',
      },
      drawer:false,
    };
  },
  methods: {
    addorder(){
      if (!this.AddNewOrderForm.shopId) {
    alert("请选择店铺");
    return;
  }
  if (!this.AddNewOrderForm.carId) {
    alert("请选择车辆");
    return;
  }
  if (!this.AddNewOrderForm.serviceId) {
    alert("请选择服务");
    return;
  }
  if (this.AddNewOrderForm.totalAmount == null) {
    alert("总金额未设置");
    return;
  }
  this.$http.post('/order/order/addNewOrder',this.AddNewOrderForm).then(resp => {
    if (resp.data.code === 200) {
      console.log(resp.data.data);
      this.$message({
        type: 'success',
        message: '下单成功'
      });
      
    }

  })
      console.log(this.AddNewOrderForm);

    },
    
    addservers(obj){
      this.AddNewOrderForm.serviceId = obj.serviceId;
      this.AddNewOrderForm.totalAmount = obj.servicePrice;
      this.isShow = false;
    },

    addcar(obj){
      this.AddNewOrderForm.carId = obj.carId;
      this.drawer= false;
    },
    gatcatList(){
      this.$http.post('/car/carInfo/selectcarinfo',this.SelectCarInfoForm).then(resp => {
        if (resp.data.code === 200) {
          console.log(resp.data.data);
          this.carList= resp.data.data.records;
          console.log(this.carList);
         
        }
      })
     
    },
    gatcat(){
      this.gatcatList();
      this.drawer= true;

    },
    // 格式化价格方法
    formatPrice(value) {
      if (value !== undefined && value !== null) {
        return `￥${parseFloat(value).toFixed(2)}`;
      }
      return 'N/A';
    },

    // 格式化日期方法
    formatDate(date) {
      if (date) {
        return new Date(date).toLocaleString();
      }
      return 'N/A';
    },

    // 构建查询参数
    buildParams() {
      return {
        ...this.FindServiceUserForm.pageForm,
        shopId: this.FindServiceUserForm.shopId,
        serviceName: this.FindServiceUserForm.serviceName,
        serviceCategoryId: this.FindServiceUserForm.serviceCategoryId,
        state: this.FindServiceUserForm.state,
        servicePrice: this.FindServiceUserForm.servicePrice
      };
    },

    // 获取店铺服务详情
    findServiceByShopIdUser() {
      const params = this.buildParams();

      this.$http.get('/serve/serviceDetails/findServiceByShopIdUser', { params })
        .then(resp => {
          const data = resp.data.data.list || [];
          
          // 解析 serviceItems 和 serviceProcesses 字符串为对象，并添加错误处理
          this.shopService = data.map(item => ({
            ...item,
            serviceItems: this.parseJson(item.serviceItems, []),
            serviceProcesses: this.parseJson(item.serviceProcesses, [])
          }));

          console.log(this.shopService);
        })
        .catch(error => {
          console.error('Error fetching service details:', error);
        }).catch(error => {
          console.error("获取失败:", error);
          this.$message.error("获取失败，请稍后再试。");
        });
    },

    // JSON 解析方法，带错误处理
    parseJson(str, defaultValue) {
      try {
        return Array.isArray(str) ? str : JSON.parse(str);
      } catch (e) {
        console.warn('Failed to parse JSON:', str, e);
        return defaultValue;
      }
    },

    // 查看商家服务
    viewShopServices(shopItem) {
      this.AddNewOrderForm.shopId= shopItem.shopId;
      this.isShow = true;
      this.FindServiceUserForm.shopId = shopItem.shopId;
      this.findServiceByShopIdUser();
    },

    // 展示图片
    showImage(imageSrc) {
      this.currentImage = imageSrc;
      this.dialogVisible = true;
    },

    // 关闭对话框时触发
    onDialogClose() {
      this.currentImage = '';
    },

    // 获取店铺信息列表
    getShopInfoList() {
      this.$http.post("/market/shopInfo/getShopInfoList", this.PageForm)
        .then(resp => {
          this.shopList = resp.data.data.list || []; // 确保返回的是数组
          console.log(this.shopList);
        })
        .catch(error => {
          console.error('Error fetching shop info list:', error);
        }).catch(error => {
          console.error("获取失败:", error);
          this.$message.error("获取失败，请稍后再试。");
        });
    }
  },
  created() {
    this.getShopInfoList();
    this.gatcatList();
  }
};
</script>

<style scoped>
/* 自定义样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-group {
  text-align: right;
  margin-top: 10px;
}

.el-descriptions-item__label {
  width: 100px;
}

.el-descriptions-item__content {
  word-break: break-all;
}

.enlarged-photo {
  max-width: 100%;
  max-height: 80vh;
  margin: auto;
  display: block;
}
</style>